<script setup>
import NavBar from "@/components/common/navbar/NavBar.vue";
import {register} from '@/network/user'
import {reactive, toRefs} from "vue";
import {closeNotify, showNotify, showSuccessToast} from "vant";
import {useRouter} from "vue-router";

const userInfo = reactive({
	name: '',
	email: '',
	password: '',
	password_confirmation: ''
})
const {name, email, password, password_confirmation} = toRefs(userInfo)
const router = useRouter()
const onSubmit = () => {
	// 判断两次密码是否一致
	if (password.value !== password_confirmation.value) {
		showNotify('两次密码不一致');
	} else {
		// 提交服务器处理数据
		register(userInfo).then(res => {
			console.log(res)
			if (res.status === 201) {
				// 提示信息：注册成功
				showSuccessToast('注册成功')
				// 注册成功则一秒后跳转到登录页面
				setTimeout(() => {
					closeNotify();
					router.push({path: '/login'})
					// 将表单清空
					name.value = '';
					email.value = '';
					password.value = '';
					password_confirmation.value = '';
				}, 2000)


			}
		})

	}

}
</script>

<template>
	<div>
		<nav-bar>
			<template v-slot:default>用户注册</template>
		</nav-bar>
		<div style="margin-top: 50px">
			<div style="text-align: center">
				<van-image fit="contain" height="5rem" src="https://www.lmonkey.com/_nuxt/img/logo.2a324bb.png" width="10rem">

				</van-image>
			</div>
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field
						v-model="name"
						:rules="[{ required: true, message: '请填写用户名' }]"
						label="用户名"
						name="用户名"
						placeholder="用户名"
					/>
					<van-field
						v-model="password"
						:rules="[{ required: true, message: '请填写密码' }]"
						autocomplete="on"
						label="密码"
						name="密码"
						placeholder="密码"
						type="password"
					/>
					<van-field
						v-model="password_confirmation"
						:rules="[{ required: true, message: '请填写密码' }]"
						autocomplete="on"
						label="确认密码"
						name="确认密码"
						placeholder="确认 密码"
						type="password"
					/>
					<van-field
						v-model="email"
						:rules="[{ required: true, message: '请填写用户名' }]"
						label="电子邮箱"
						name="电子邮箱"
						placeholder="电子邮箱"
					/>
				</van-cell-group>
				<div style="margin: 16px;">
					<van-button block color="#42b983" native-type="submit" round type="primary">
						提交
					</van-button>
					<div class="link-login" @click="router.push({path:'/login'})">已有账号？立即登录</div>
				</div>
			</van-form>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.link-login {
	line-height: 50px;
	font-size: 14px;
	margin-bottom: 20px;
	color: #42b983;
	display: inline-block;
}
</style>